<template>
  <el-row>
    <el-col>
      <el-form ref="formRef" :model="form.data" inline>
        <el-form-item label="创建时间：">
          <el-date-picker v-model="form.data.date" type="daterange" range-separator="-" start-placeholder="开始时间"
                          end-placeholder="结束时间" @change="changeTime" :clearable="false"/>
        </el-form-item>
        <el-form-item label="角色名称：">
          <el-input v-model="form.data.roleName" clearable placeholder="请输入角色名称"
                    style="width: 202px !important;"></el-input>
        </el-form-item>
        <el-form-item label="状态：">
          <el-select v-model="form.data.status" placeholder="请选择" clearable>
            <el-option v-for="item in statusList.data" :key="item.value" :label="item.name" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="search">搜索</el-button>
          <el-button icon="Refresh" @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <el-col class="global_operation_wrapper">
      <el-button type="primary" icon="Plus" size="small" plain @click="handAdd">新增</el-button>
      <el-button type="danger" icon="Delete" size="small" plain :disabled="!multipleSelection.data.length > 0"
                 @click="handDelete">
        批量删除
      </el-button>
      <!--                <el-button type="warning" icon="Download" size="small" plain @click="handExport">导出</el-button>-->
    </el-col>
    <el-col class="global_table_wrapper">
      <el-table ref="multipleTableRef" :data="dataList.data" highlight-current-row stripe :cell-class-name="cellClass"
                :cell-style="{ textAlign: 'center' }" :header-cell-style="{ textAlign: 'center',background:'#f8f8f9' }"
                max-height="460" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"/>
        <el-table-column label="角色名称" prop="roleName" :show-overflow-tooltip="true"/>
        <el-table-column label="权限字符" prop="roleKey" :show-overflow-tooltip="true"/>
        <el-table-column label="显示顺序" prop="roleSort" :show-overflow-tooltip="true"/>
        <el-table-column label="状态" prop="status" :show-overflow-tooltip="true">
          <template #default="{row}">
            <el-switch v-model="row.status" :disabled="row.roleKey == 'admin'" inline-prompt size="large"
                       active-text="启用" inactive-text="停用"
                       :active-value="1" :inactive-value="0" @change="changeRoleStatus(row)"/>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" :show-overflow-tooltip="true"/>
        <el-table-column label="备注" prop="remark" :show-overflow-tooltip="true"/>
        <el-table-column fixed="right" label="操作" width="300">
          <template #default="{row}">
            <el-button @click="editRole(row)" type="warning" icon="Edit" size="small" v-if="row.roleKey != 'admin'">
              编辑
            </el-button>
            <el-button @click="deleteRole(row)" type="danger" icon="Delete" size="small" v-if="row.roleKey != 'admin'">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <Pagination :total="form.data.total" v-model:page="form.data.pageNo" v-model:limit="form.data.pageSize"
                    @pagination="initialize"/>
      </div>
    </el-col>
  </el-row>
  <!--  新增/编辑角色弹框-->
  <DialogRole ref="dialogRoleRef" :id="dialogRoleId" :index="dialogRoleIndex" @refresh-the-list="initialize()"/>
</template>

<script setup lang="ts">
import DialogRole from '@/views/system/role/components/dialogRole.vue'
import Pagination from '@/components/Pagination/index.vue'
import dayjs from "dayjs";
import baseRequest from "@/service/baseRequest";
import {useRouter} from "vue-router";
import {ElMessage, ElMessageBox} from "element-plus";

let form = reactive({
  data: {
    date: [],
    startTime: '',
    endTime: '',
    roleName: '',
    status: '',
    pageNo: 1,
    pageSize: 10,
    total: 0
  }
})
let dataList = reactive({
  data: []
})
let statusList = reactive<{ data: Array<Record<string, string | number>> }>({
  data: [
    {name: '正常', value: 1},
    {name: '停用', value: 0},
  ]
})
const multipleSelection = reactive<{ data: any[] }>({
  data: []
})
const formRef = ref()
const multipleTableRef = ref()
const router = useRouter()
const dialogRoleRef = ref()
let dialogRoleId = ref()
let dialogRoleIndex = ref()
const changeTime = (e: any) => {
  if (e && e.length > 0) {
    form.data.startTime = dayjs(e[0]).format('YYYY-MM-DD 00:00:00')
    form.data.endTime = dayjs(e[1]).format('YYYY-MM-DD 23:59:59')
  } else {
    form.data.startTime = ''
    form.data.endTime = ''
  }
}
const search = () => {
  initialize()
}
onMounted(() => {
  initialize()
})
const initialize = async () => {
  const sendData = JSON.parse(JSON.stringify(form.data))
  delete sendData.date
  console.log(sendData)
  const response = await baseRequest.get('/roleList', sendData) as any
  dataList.data = response.data.list
  form.data.total = response.data.total
}
const cellClass = (data: Record<string, any>) => {
  if (data.row.roleKey == 'admin') return 'myCell'
}
//新增角色
const handAdd = () => {
  dialogRoleIndex.value = 1
  nextTick(() => {
    dialogRoleRef.value.dropDownBoxQuery()
    dialogRoleRef.value.dialogComVisible = true
  })
}
//批量删除
const handDelete = () => {
  if (multipleSelection.data.length > 0) {
    const roleNameList = multipleSelection.data.map(item => item.roleName)
    ElMessageBox.confirm(
        `确定删除 ${roleNameList.join(' , ')} 吗？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    )
        .then(async () => {
          const idList = multipleSelection.data.map(item => item.id)
          const deleteRes = await baseRequest.delete('/deleteRole', {ids: idList}) as any
          if (deleteRes.code == 200) {
            ElMessage.success('删除成功')
            initialize()
          }
        }).catch(() => {
    })
  }
}
//列表开关
const changeRoleStatus = async (row: Record<string, any>) => {
  if (row.status == 0) {
    const changeRoleRes = await baseRequest.post('/changeRole', {status: 0}) as any
    if (changeRoleRes.code == 200) {
      ElMessage.success('停用角色成功')
      initialize()
    }
  } else {
    const changeRoleRes = await baseRequest.post('/changeRole', {status: 1}) as any
    if (changeRoleRes.code == 200) {
      ElMessage.success('启用角色成功')
      initialize()
    }
  }
}
//编辑角色
const editRole = (row: Record<string, any>) => {
  dialogRoleId.value = row.id
  dialogRoleIndex.value = 2
  nextTick(() => {
    dialogRoleRef.value.dropDownBoxQuery()
    dialogRoleRef.value.backShow()
    dialogRoleRef.value.dialogComVisible = true
  })
}
//行内删除
const deleteRole = (row: Record<string, any>) => {
  ElMessageBox.confirm(
      `确定删除该角色信息吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        const deleteRes = await baseRequest.delete('/deleteRole', {id: row.id}) as any
        if (deleteRes.code == 200) {
          ElMessage.success('删除成功')
          initialize()
        }
      }).catch(() => {
  })
}
//批量勾选后赋值
const handleSelectionChange = (val: any[]) => {
  multipleSelection.data = val.filter(item => item.roleKey != 'admin')
}
const reset = () => {
  form.data = {
    date: [],
    startTime: '',
    endTime: '',
    roleName: '',
    status: '',
    pageNo: 1,
    pageSize: 10,
    total: 0
  }
  initialize()
}
</script>

<style lang="scss" scoped>
:deep(.myCell .el-checkbox__input) {
  display: none !important;
}
</style>
